package com.ccx.coachsite.ui.customview;




import com.ccx.coachsite.data.SystemConst;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;

/**
 * 支持横向滑屏ViewGroup <br>
 */
public abstract class LazyViewPager extends ViewPager {
	public static final String TAG = "LazyViewPager";
	private boolean isFirstMeasure = true;
	/**
	 * 确保初始化加载仅执行一次
	 */
	private boolean [] lazyLoaded;
	
	public LazyViewPager(Context context) {
		super(context);
	}

	public LazyViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public LazyViewPager(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (isFirstMeasure) {
			final int N = this.getChildCount();
			lazyLoaded = new boolean[N];
			for (int i = 0; i < N; i++) {
				lazyLoaded[i] = false;
			}
			isFirstMeasure = false;
		}
		
		int initLoad = (getChildCount() - 1) / 2;
		
		if (init != SystemConst.NO_DATA && init >= 0 && init < getChildCount())
			initLoad = init;
    			
		if (!lazyLoaded[initLoad]) {
			lazyLoaded[initLoad] = loadContentData(initLoad);
		}
	}

	/**
	 * 处理延迟加载
	 */
	@Override
	public void snapToScreen(int whichScreen) {
		super.snapToScreen(whichScreen);
		if (whichScreen < 0 || whichScreen >= lazyLoaded.length) {
			Log.e(TAG, "LazyViewPager ERROR!!!!!!!!");
			return;
		}
		if (!lazyLoaded[whichScreen]) {
			lazyLoaded[whichScreen] = loadContentData(whichScreen);
		}
	}

	/**
	 * 延迟加载指定屏幕
	 */
	protected abstract boolean loadContentData(int screen);
}
